package com.cpecc.liucheng.dao;

import com.cpecc.liucheng.model.LiuChengUser;
import com.cpecc.model.system.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import org.wisteria.framework.web.mvc.constant.ShanChuBZ;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class LiuChengRenYuanDao {

    @Resource
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public void save(LiuChengUser entity){
        Session session= getSession();
        session.save(entity);
        session.flush();
    }

    public Query getQuery(String hql) {
        return getSession().createQuery(hql);
    }

    public int delete(String id){
        String hql="update LiuChengUser t set t.shanChuBZ = ? where t.id = ?";
        Query query = getQuery(hql);
        query.setInteger(0, ShanChuBZ.YI_SHANCHU.getValue());
        query.setString(1, id);
        return query.executeUpdate();
    }

    public int updateChuLiJG(String liuChengId, Integer huanJieId, String userId, Integer chuLiJG) {
        String hql="update LiuChengUser t set t.chuLiJG = ? where t.liuChengId = ? and t.huanJieId = ? and t.user.id = ?";
        Query query = getQuery(hql);
        query.setInteger(0, chuLiJG);
        query.setString(1, liuChengId);
        query.setInteger(2, huanJieId);
        query.setString(3, userId);
        return query.executeUpdate();
    }

    public List<User> listUser(String liuChengId, Integer huanJieId) {
        String hql="select t.user from LiuChengUser t where t.chuLiJG = 0 and t.liuChengId = ? and t.huanJieId = ?";
        Query query = getQuery(hql);
        query.setString(0, liuChengId);
        query.setInteger(1, huanJieId);
        return query.list();
    }

    public List<LiuChengUser> list(String liuChengId, Integer huanJieId, String userId) {
        String hql ="from LiuChengUser t where t.shanChuBZ = 0";
        if (StringUtils.hasText(liuChengId)) {
            hql += " and t.liuChengId = :liuChengId";
        }
        if (huanJieId != null) {
            hql += " and t.huanJieId = :huanJieId";
        }
        if (StringUtils.hasText(userId)) {
            hql += " and t.user.id = :userId";
        }

        Map<String, Object> bean = new HashMap();
        bean.put("liuChengId", liuChengId);
        bean.put("huanJieId", huanJieId);
        bean.put("userId", userId);

        Query query = getQuery(hql);
        query.setProperties(bean);
        return query.list();
    }
}
